package cn.stylefeng.guns.modular.gridsystem.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.core.annotion.BusinessLog;
import cn.stylefeng.guns.core.enums.LogAnnotionOpTypeEnum;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.pojo.response.ErrorResponseData;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.modular.gridsystem.constants.GatewayTaskTypeConstant;
import cn.stylefeng.guns.modular.gridsystem.constants.GatewayTypeCodeConstant;
import cn.stylefeng.guns.modular.gridsystem.entity.BizChannelType;
import cn.stylefeng.guns.modular.gridsystem.entity.BizFosInfo;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGatewayChannel;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizAmpLogParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizFosInfoParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizGatewayChannelParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.BizGatewayChannelResult;
import cn.stylefeng.guns.modular.gridsystem.service.BizChannelTypeService;
import cn.stylefeng.guns.modular.gridsystem.service.BizFosInfoService;
import cn.stylefeng.guns.modular.gridsystem.service.BizGatewayChannelService;
import cn.stylefeng.guns.modular.gridsystem.service.GatewayTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * biz_gateway_channel 控制器
 *
 * @author: ssy
 * @date: 2021/09/14 11:47
 */
@RestController
@RequiredArgsConstructor
public class BizGatewayChannelController {

    private final BizGatewayChannelService bizGatewayChannelService;

    private final BizChannelTypeService bizChannelTypeService;

    private final BizFosInfoService bizFosInfoService;

    private final GatewayTaskService taskService;

    /**
     * 分页查询biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGatewayChannel/page")
    @BusinessLog(title = "biz_gateway_channel_分页查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(BizGatewayChannelParam bizGatewayChannelParam) {
        return new SuccessResponseData(bizGatewayChannelService.pageList(bizGatewayChannelParam));
    }

    /**
     * 获取全部biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGatewayChannel/list")
    @BusinessLog(title = "biz_gateway_channel_查询所有", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(BizGatewayChannelParam param) {
        List<BizGatewayChannelResult> channelList = bizGatewayChannelService.list(param).stream().map(item -> {
            if (ObjectUtil.isEmpty(item.getDeviceId())) {
                item.setDeviceId(0);
            }
            return item;
        }).collect(Collectors.toList());
        return new SuccessResponseData(channelList);
    }

    /**
     * 根据网关主键获取所有通道
     */
    @GetMapping("/bizGatewayChannel/listChannel")
    @BusinessLog(title = "根据网关主键获取所有通道", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData listChannel(BizGatewayChannelParam param) {
        return new SuccessResponseData(bizGatewayChannelService.listChannel(param));
    }

    /**
     * 查看详情biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGatewayChannel/detail")
    @BusinessLog(title = "biz_gateway_channel_查看详情", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(BizGatewayChannelParam.detail.class) BizGatewayChannelParam bizGatewayChannelParam) {
        return new SuccessResponseData(bizGatewayChannelService.detail(bizGatewayChannelParam));
    }

    /**
     * 添加biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGatewayChannel/add")
    @BusinessLog(title = "biz_gateway_channel_增加", opType = LogAnnotionOpTypeEnum.ADD)
    @Transactional(rollbackFor = Exception.class)
    public ResponseData add(@RequestBody @Validated({BizGatewayChannelParam.add.class}) BizGatewayChannelParam bizGatewayChannelParam) {
        Integer count = bizGatewayChannelService.countByDIdAndChannel(bizGatewayChannelParam);
        if (count == 0) {
            bizGatewayChannelParam.setCreatedAt(DateUtil.date());
            bizGatewayChannelService.add(bizGatewayChannelParam);
            final BizChannelType channelType = bizChannelTypeService.getById(bizGatewayChannelParam.getChannelType());
            if (channelType.getCode().equals(GatewayTypeCodeConstant.FIBRE_OPTICAL_SENSORS_CODE)) {
                BizFosInfoParam bizFosInfoParam = new BizFosInfoParam();
                bizFosInfoParam.setChannelId(bizGatewayChannelParam.getId());
               /* if(!NumberUtil.isNumber(bizGatewayChannelParam.getStartPoint()) || !NumberUtil.isNumber(bizGatewayChannelParam.getEndPoint()) ){
                    throw new ServiceException("开始点位为非数字类型或结束点位为非数字类型");
                }*/
                if(ObjectUtil.compare(bizGatewayChannelParam.getStartPoint(),"200") < 0){
                    throw new ServiceException("侦听点位必须大于等于200");
                }
                bizFosInfoParam.setStartPoint(bizGatewayChannelParam.getStartPoint());

                BizGatewayChannelParam channelParam = new BizGatewayChannelParam();
                channelParam.setGatewayId(bizGatewayChannelParam.getGatewayId());
                List<BizGatewayChannelResult> channelResultList = bizGatewayChannelService.listChannel(channelParam);
                Optional<BizGatewayChannelResult> bizGatewayChannelResult = channelResultList.stream().filter(channelResult -> {
                            int startPointCount = bizFosInfoService.count(new LambdaQueryWrapper<BizFosInfo>().eq(BizFosInfo::getStartPoint,bizGatewayChannelParam.getStartPoint()));
                            return startPointCount > 0 ;
                        }
                ).findFirst();

                if (!bizGatewayChannelResult.isPresent()) {
                    bizFosInfoService.add(bizFosInfoParam);
                } else {
                    throw new ServiceException("已存在通道在该点位范围内");
                }

            }
            return new SuccessResponseData();
        } else {
            throw new ServiceException("该通道已存在");
        }
    }

    /**
     * 删除biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGatewayChannel/delete")
    @BusinessLog(title = "biz_gateway_channel_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(BizGatewayChannelParam.delete.class) BizGatewayChannelParam bizGatewayChannelParam) {
        bizGatewayChannelService.delete(bizGatewayChannelParam);
        return new SuccessResponseData();
    }

    /**
     * 编辑biz_gateway_channel
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGatewayChannel/edit")
    @BusinessLog(title = "biz_gateway_channel_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    @Transactional(rollbackFor = Exception.class)
    public ResponseData edit(@RequestBody @Validated(BizGatewayChannelParam.edit.class) BizGatewayChannelParam bizGatewayChannelParam) {
        final boolean update = bizGatewayChannelService.edit(bizGatewayChannelParam);

        if (update) {
            final BizChannelType channelType = bizChannelTypeService.getById(bizGatewayChannelParam.getChannelType());
            if (channelType.getCode().equals(GatewayTypeCodeConstant.FIBRE_OPTICAL_SENSORS_CODE)) {
                LambdaQueryWrapper<BizFosInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BizFosInfo::getChannelId, bizGatewayChannelParam.getId());
                BizFosInfo fosInfo = bizFosInfoService.getOne(queryWrapper);
                BizFosInfo bizFosInfo = new BizFosInfo();
                if (ObjectUtil.isNotNull(fosInfo)) {
                    bizFosInfo.setId(fosInfo.getId());
                }
                bizFosInfo.setChannelId(bizGatewayChannelParam.getId());
                bizFosInfo.setStartPoint(bizGatewayChannelParam.getStartPoint());
                bizFosInfo.setEndPoint(bizGatewayChannelParam.getEndPoint());
                boolean saveOrUpdate = bizFosInfoService.saveOrUpdate(bizFosInfo);
                //下发更新侦听点任务
                if(saveOrUpdate){
                    Map<String, Object> map = new HashMap<>();
                    map.put("opticalListeningLocation", bizGatewayChannelParam.getStartPoint());
                    map.put("channel", bizGatewayChannelParam.getChannel());
                    List<Integer> gatewayIds = new ArrayList<>();
                    gatewayIds.add(bizGatewayChannelParam.getGatewayId());
                    taskService.add(GatewayTaskTypeConstant.SYNC_OPTICAL_LISTENING_LOCATION, gatewayIds, JSONUtil.toJsonStr(map));
                }
            }
        }

        return new SuccessResponseData();
    }

    /**
     * 通道解绑
     */
    @PostMapping("/bizGatewayChannel/unbinding")
    @BusinessLog(title = "通道解绑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData unbinding(@RequestBody @Validated(BizGatewayChannelParam.unbinding.class) BizGatewayChannelParam param) {
        bizGatewayChannelService.unbinding(param);
        return new SuccessResponseData();
    }

    /**
     * 通道标记
     */
    @PostMapping("/bizGatewayChannel/mark")
    @BusinessLog(title = "通道解绑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData mark(@RequestBody @Validated(BizGatewayChannelParam.mark.class) BizGatewayChannelParam param) {
        bizGatewayChannelService.mark(param);
        return new SuccessResponseData();
    }

    /**
     * 查询通道绑定信息
     *
     * @author zxw 2022-12-02 10:20
     */
    @GetMapping("/bizGatewayChannel/queryChannelBindingInfo")
    @BusinessLog(title = "查询通道绑定信息", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData queryChannelBindingInfo(BizGatewayChannelParam param) {
        return new SuccessResponseData(bizGatewayChannelService.queryChannelBindingInfo(param));
    }

    @PostMapping("/bizGatewayChannel/editById")
    public ResponseData editById(@RequestBody BizGatewayChannelParam bizGatewayChannelParam) {
        bizGatewayChannelService.editById(bizGatewayChannelParam);
        return new SuccessResponseData();
    }

    @GetMapping("/bizGatewayChannel/getChannelList")
    @BusinessLog(title = "查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public List<BizGatewayChannelResult> getChannelList(BizGatewayChannelParam bizGatewayChannelParam) {
        return bizGatewayChannelService.listByGId(bizGatewayChannelParam);
    }


    //
    /**
     * <p>根据gatewayICode channel 查询通道信息</p >
     * 获取安装位置
     * @param param
     */
    @PostMapping("/bizGatewayChannel/gatewayChannel")
    public ResponseData gatewayChannelByCodeAndChannel(@RequestBody BizGatewayChannelParam param) {
        BizGatewayChannel gatewayChannel = bizGatewayChannelService.gatewayChannelByCodeAndChannel(param);
        return new SuccessResponseData(gatewayChannel);
    }



}
